package com.EJ.ejcompanyweb.HttpURLC;

import android.os.AsyncTask;
import android.util.Log;
import android.widget.Toast;

import androidx.recyclerview.widget.RecyclerView;

import com.EJ.ejcompanyweb.adapter.MyAdapter;
import com.EJ.ejcompanyweb.entity.DateEntity;
import com.EJ.ejcompanyweb.entity.ItemEntity;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.util.ArrayList;

public class JsoupFragmentData extends AsyncTask<String,Void, ArrayList<DateEntity>> {
    private String TAG=this.getClass().getSimpleName();
    private ArrayList<DateEntity> DateEntityS=new ArrayList<DateEntity>() ;
    private RecyclerView mRecycleView;

    public JsoupFragmentData(RecyclerView mRecycleView) {
        this.mRecycleView = mRecycleView;
    }

    @Override
    protected ArrayList<DateEntity> doInBackground(String... strings) {
        GetArmariumData(strings[0]);
        return DateEntityS;
    }

    @Override
    protected void onPostExecute(ArrayList<DateEntity> dateEntities) {
        super.onPostExecute(dateEntities);

        if (dateEntities.isEmpty()){
            //Toast.makeText(mRecycleView.getContext(),"该页面暂无数据,右滑下试试",Toast.LENGTH_SHORT).show();
        }
        mRecycleView.setAdapter(new MyAdapter(dateEntities));
    }

    private void GetArmariumData(String url){
        Document doc= null;
        try {
            doc = Jsoup.connect(url).get();
        } catch (IOException e) {
            e.printStackTrace();
        }
        if(doc==null){
            return;
        }
        ArrayList<DateEntity> al2 = new ArrayList<DateEntity>();
        //product-wrapper
        Elements divs=doc.select("div.product-wrapper");
        //  product-thumb
       // Elements thumbs=divs.select("div[class=product-thumb]");//旧版本
        if (divs.size()>1){
            divs.remove(0);
        }
        Elements thumbs=divs.select("div[class=product-thumb]");//新版本
        for (Element thumb : thumbs) {

            //价格标签
            Elements price = thumb.select("p.price");
            // Log.e(TAG, price.text());

            Elements images = thumb.select("div.image");
            for (Element image : images) {
                //商品连接
                String url1 = image.select("a").attr("href");

                Elements img = image.select("img");
                //商品图像
                String BitmapUrl = img.attr("src");
                //商品名称
                String titel = img.attr("title");
                //商品介绍
                String alt=img.attr("alt");
                //Log.e(TAG, url1);
                al2.add(new DateEntity(titel,alt,url1,BitmapUrl,price.text()));

            }
        }
        for (DateEntity i:al2){
            Log.e(TAG,i.toString());
        }
        DateEntityS=al2;
    }
}
